package com.radar.task;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;
import java.util.Iterator;

@Component
@Slf4j
public class CleanTask {

    @Value("${ncPath}")
    private String ncPath;

    @Value("${tmpPath}")
    private String tmpPath;

    @Value("${ncTimeLimit}")
    private int ncTimeLimit;

    @Scheduled(cron = "0 0 0/2 * * ? ")
    public void cleanFile() {
        if (ncTimeLimit != -1) {
            timeout(ncPath, (long) (ncTimeLimit + 1) * 1000 * 60 * 60 * 24);
            timeout(tmpPath, (long) (ncTimeLimit + 2) * 1000 * 60 * 60 * 24);
        }
    }

    /**
     * 清理目录中过期的文件
     *
     * @param dirPath 文件路径
     * @param ms      时间 /毫秒
     */
    public static void timeout(String dirPath, long ms) {
        // 该日期之前的文件
        Date pointDate = new Date(System.currentTimeMillis() - ms);
        // 文件过滤条件
        IOFileFilter fileFiles = new AndFileFilter(FileFileFilter.FILE, FileFilterUtils.ageFileFilter(pointDate, true));
        File directory = new File(dirPath);
        Iterator<File> itFile = FileUtils.iterateFiles(directory, fileFiles, TrueFileFilter.INSTANCE);
        // 删除符合条件的文件
        while (itFile.hasNext()) {
            itFile.next().delete();
        }
    }

}
